package com.topgay.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.topgay.dao.DatingDAO;
import com.topgay.domain.AnswerForFYTL;
import com.topgay.domain.AnswerRaw;
import com.topgay.domain.MatchInfo;

@Service
public class DatingServiceImple implements DatingService{

	@Autowired
	private DatingDAO dao;
	
	@Override
	public int checkAnswer(String id){
		return dao.selectOneAnswer(id);
	}
	
	@Override
	public int setAnswerRaw(AnswerRaw answer, String id, String nickname) {
		
		return dao.insertAnswerRaw(answer, id, nickname);
	}

	@Override
	public ArrayList<MatchInfo> timeLineList(String id){
		id = id.toUpperCase();
		ArrayList<String> timeLineNameList = dao.selectTimeLineName(id);
		ArrayList<String> partnerNameList = new ArrayList<String>();
		ArrayList<MatchInfo> timeLineList = new ArrayList<MatchInfo>();
		
		for(String tmp : timeLineNameList){
			partnerNameList.add(parseId(id, tmp));
		}
		
		for(String tmp : partnerNameList){
			tmp = tmp.toLowerCase();
			timeLineList.add(dao.selectTimeLineInfo(tmp));
		}
		return timeLineList;
	}
	
	@Override
	public String parseId(String myId, String timeLineName){
		String splitStr1 = "";
		String splitStr2 = "";
		
		splitStr1 = timeLineName.split("_")[0];
		splitStr2 = timeLineName.split("_")[1];
		
		if(myId.equals(splitStr1)){
			return splitStr2;
		}else{
			return splitStr1;
		}
	}
	
	@Override
	public ArrayList<MatchInfo> searchList(String id) {
		ArrayList<MatchInfo> list = new ArrayList<MatchInfo>();
		ArrayList<AnswerForFYTL> an = new ArrayList<AnswerForFYTL>();
		
		list = dao.selectAllAnswer();
		
		for(int i = 0; i < list.size(); i++){
			if(list.get(i).getId().equals(id)){
				an = list.get(i).getAnswerList();
				break;
			}
		}
		
		for(MatchInfo tmp : list){
			tmp.setMatchPercent(this.matchingAlgorithm(tmp.getAnswerList(), an));
		}
		
		Collections.sort(list);
		
		return list;
	}
	
	@Override
	public float matchingAlgorithm(ArrayList<AnswerForFYTL> a, ArrayList<AnswerForFYTL> an){
		float matchingPercent = 0;
		
		for(int i = 0; i < a.size(); i++){
			if(a.get(i).getAnswer() == an.get(i).getAnswer()){
				switch(a.get(i).getNo()){
				case 3:
					matchingPercent += 4.5;
					break;
				case 18:
					matchingPercent += 4.5;
					break;
				case 20:
					matchingPercent += 4.5;
					break;
				case 2:
					matchingPercent += 6.1;
					break;
				case 12:
					matchingPercent += 6.1;
					break;
				case 21:
					matchingPercent += 6.1;
					break;
				case 4:
					matchingPercent += 7.3;
					break;
				case 10:
					matchingPercent += 7.3;
					break;
				case 16:
					matchingPercent += 7.3;
					break;
				default:
					matchingPercent += 3.3;
					break;
				}
			}
		}
		return (float)(Math.round(matchingPercent*1000)/1000.0);
	}
}
